package uk.co.leandro.views
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.GlowFilter;
	
	import flashx.textLayout.elements.BreakElement;
	
	import uk.co.leandro.events.GemEvent;
	
	public class Gem extends Sprite
	{
		public static const BLUE:int = 0;
		public static const GREEN:int = 1;
		public static const PURPLE:int = 2;
		public static const RED:int = 3;
		public static const YELLOW:int = 4;
		
		public var colourIndex:Number = 0;
		public var row:int = 0;
		public var column:int = 0;
		public var destroy:Boolean = false;
		
		[Embed(source="assets/Blue.png")]
		private var BlueClass:Class;
		
		[Embed(source="assets/Green.png")]
		private var GreenClass:Class;
		
		[Embed(source="assets/Purple.png")]
		private var PurpleClass:Class;
		
		[Embed(source="assets/Red.png")]
		private var RedClass:Class;
		
		[Embed(source="assets/Yellow.png")]
		private var YellowClass:Class;
		
		//public static var randomise:Object;
		
		private var gemBitmap:Bitmap;
		private var selected:Boolean = false;
		
		public function Gem(r:int, c:int)
		{
			row = r;
			column = c;
			randomise();
			
			addEventListener(MouseEvent.CLICK, clickHandler);
		}

		protected function clickHandler(event:MouseEvent):void
		{
			dispatchEvent(new GemEvent(GemEvent.CLICKED, this));
		}

		public function select():void
		{
			selected = true;
			// Apply glow
			var glow:GlowFilter = new GlowFilter();
			glow.color = 0x66FF99;
			glow.alpha = 1;
			glow.blurX = 10;
			glow.blurY = 10;
			glow.quality = BitmapFilterQuality.LOW; 
			
			filters = [glow];
			dispatchEvent(new GemEvent(GemEvent.SELECTED, this));
		}
		
		public function deselect():void
		{
			selected = false;
			filters = [];
			dispatchEvent(new GemEvent(GemEvent.DESELECTED, this));
		}
		
		private function addGemBitmap(gemType:int):void
		{
			if (gemBitmap != null) removeChild(gemBitmap);
			
			switch(gemType)
			{
				case BLUE:
					gemBitmap = new BlueClass();
					break;
				case GREEN:
					gemBitmap = new GreenClass();
					break;
				case PURPLE:
					gemBitmap = new PurpleClass();
					break;
				case RED:
					gemBitmap = new RedClass();
					break;
				default:
					gemBitmap = new YellowClass();
			}
			addChild(gemBitmap);
		}
		
		public function randomise():void
		{
			colourIndex = Math.floor(Math.random() * 5);
			addGemBitmap(colourIndex);
		}
	}
}